<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.prop === 'invoiceType'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
              Select(v-if="item.prop === 'serverName'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'radio'")
              RadioGroup(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="c_item of item.radioArr" :label="c_item.label") {{c_item.label}}
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval(:value="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker(item.model1, $event)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval(:value="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker(item.model2, $event)")
            template(v-if="item.type === 'button'")
              Button(v-if="hasFind" type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable")
          .clearfix.font-16(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |开票总额
              span.text-info.pl-5.pr-5.font-weight {{tableComone.total}}
              |元
            .pull-right.table-title-btns
              //- Upload.display-inline-block.mr-10(
              //-   :before-upload="handleBeforeUploadImportInvoice"
              //-   :data="{companyId: companyId, companyName: companyName}"
              //-   :show-upload-list="false"
              //-   accept=".xls, .xlsx"
              //-   :action="baseUrl + 'api/Invoice/ImportInvoice'"
              //-   :on-success="uploadSuccessImportInvoice"
              //- )
              //-   Button(type="info" size="small") 批量导入(当前页面)
              Button.mr-10(v-if="hasImportInvoice" type="info" @click="handleShowBatchImportModal") 批量导入
              Button.mr-10(v-if="hasExportInvoiceKFC" type="info" @click="exportInvoiceKFC") 导出KFC
              Button.mr-10(v-if="hasExportInvoice" type="info" @click="exportInvoice") 导出
              Button.mr-10(type="info" @click="exportReceiveIncome") 导出应收单-U8
              Button(type="info" @click="exportReceiveCost") 导出应付单-U8
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    //- 是否下载错误模板
    ErrorTemplateModal(ref="ErrorTemplateModal")

    //- 批量导入弹窗
    BatchImportModal(ref="BatchImportModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { InvoiceApi } from '@/api/Invoice.api.js'
import { ReceivableBillApi } from '@/api/ReceivableBill.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { InvoiceWriteThead } from './SOtableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import ErrorTemplateModal from '@/components/errorTemplateModal.vue'
import BatchImportModal from './modal/batchImportModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '', // 发票开具汇总页面

  components: {
    ErrorTemplateModal,
    BatchImportModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(InvoiceWriteThead),
      tableData: [],
      formData: {
        companyName: '',
        companyCode: '',
        companyLegalName: '',
        startDate: new Date(),
        endDate: new Date(),
        status: '',
        invoiceType: '',
        serverName: ''
      },
      formItem: [
        { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'companyName', model: 'companyName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6' },
        { type: 'input', label: '客户编码：', placeholder: '请输入客户编码', prop: 'companyCode', model: 'companyCode', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6' },
        { type: 'input', label: '客户法定名称：', placeholder: '请输入客户法定名称', prop: 'companyLegalName', model: 'companyLegalName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6' },
        // {type: 'radio', label: '开票状态', placeholder: '请选择开票状态', prop: 'status', model: 'status', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6', radioArr: [{value: '1', label: '已开具'}, {value: '0', label: '未开具'}]},
        { type: 'select', label: '发票类型：', placeholder: '请选择发票类型', prop: 'invoiceType', model: 'invoiceType', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6', options: 'invoicetype' },
        { type: 'select', label: '所属客服：', placeholder: '请选择所属客服', prop: 'serverName', model: 'serverName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6', options: 'server' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-7 ivu-col-span-xxl-6' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-3 ivu-col-span-xxl-3' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 开票总额
      },
      downLoadRul: '',
      arrListDown: {
        invoiceitem: [],
        invoicetype: [],
        server: [],
        invoiceRate: [{ label: '0%', value: '0%' }, { label: '5%', value: '5%' }, { label: '6%', value: '6%' }]
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      importInvoiceFile: null
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出
    hasExportInvoice () {
      return this.actionArr.indexOf('ExportInvoice') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('GetInvoiceList') > -1
    },
    // 批量导入
    hasImportInvoice () {
      return this.actionArr.indexOf('ImportInvoice') > -1
    },
    // 导出kfc
    hasExportInvoiceKFC () {
      return this.actionArr.indexOf('ExportInvoiceKFC') > -1
    }
  },

  mounted () {
    this.query()
    this.servers()
    this.getEnum()
  },

  methods: {
    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    // 数据字典
    getEnum () {
      let groupName = 'invoice.invoiceitem,invoice.invoicetype'
      Common.getEnum(groupName, this.arrListDown)
      // console.log('数据字典：', this.arrListDown)
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await InvoiceApi.getInvoiceList({ ...params, ...this.formData })
      console.log('发票开具汇总res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ' + model + ', val: ', val)
      this.formData[model] = val
      // this.getDayList()
    },

    // 导出
    async exportInvoice () {
      let res = await InvoiceApi.exportInvoice(this.formData)
      console.log('导出res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出KFC
    async exportInvoiceKFC () {
      let res = await InvoiceApi.exportInvoiceKFC(this.formData)
      console.log('导出KFCres: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出应收账单
    async exportReceiveIncome () {
      let res = await InvoiceApi.exportReceiveIncome()
      console.log('导出res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出应付账单
    async exportReceiveCost () {
      let res = await InvoiceApi.exportReceiveCost()
      console.log('导出res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 批量导入-上传前文件
    handleBeforeUploadImportInvoice (file) {
      this.importInvoiceFile = file
      console.log('file: ', this.importInvoiceFile)
    },

    // 批量导入成功(当前页面fn)
    uploadSuccessImportInvoice (res) {
      console.log('批量导入res: ', res)
      if (res.code === 200 && res.success) {
        if (res.data) {
          if (res.data) {
            // this.$Message.error('上传有错误，你可以下载错误数据文件')
            // window.open(baseUrl + res.data, '_blank')
            this.$refs.ErrorTemplateModal.downloadUrl = res.data
            this.$refs.ErrorTemplateModal.isShowErrorTemplateModal = true
          } else {
            this.$Message.success(res.message)
            this.query()
          }
        } else {
          this.$Message.success(res.message)
          this.query()
        }
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 批量导入-显示弹窗
    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.file = null
      this.$refs.BatchImportModal.errorData.isError = false
      this.$refs.BatchImportModal.show()
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
